<template>
  <div class="w12 dld_body">
    <div class="jl_form">
      <div class="jl_form_item" @click="open">
        <span class="w04" style="color: gray"><em class="font_red" v-if="required">*</em>{{label}}</span>
        <span class="w08 tr">{{addressName || '请选择省市区'}}</span>
        <i class="fa fa-angle-right"></i>
      </div>
      <textarea class="w12 pr15 mb10" placeholder="请输入详细地址，街道，门牌号等。"
                v-model="detailJson.VALUE"></textarea>
    </div>

    <div class="settlement_modal" v-if="show">
      <div class="settlement_modal_bg" @click="close"></div>
      <div class="address_add">
        <h3>选择地区</h3>
        <ul class="address_add_tab">
          <template v-for="item in tabsList">
            <li :class="{'true':'xuan'}[getTabsSelected(item)]"
                @click="changeTabs(item)">
              {{item['VALUE']}}
            </li>
          </template>
        </ul>
        <div class="address_add_main">
          <template v-for="item in contentList">
          <span :class="{'true':'xuan'}[isSelected(item)]" @click="selected(item)">
            {{item['VALUE']}}
            <template v-if="isSelected(item)">
              <i class="fa fa-check"></i>
            </template>
          </span>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import * as http from '../plugins/http'

  export default {
    name: 'jl-address',
    props: {
      label: {
        type: String
      },
      required: {
        type: Boolean,
        default: false
      },
      value: {
        type: Array,
        default: () => {
          return []
        }
      }
    },
    data() {
      return {
        tabs: {},
        tabsCard: {},
        tabsList: [{
          VALUE: '请选择'
        }],
        contentList: [],
        show: false,
        addressName: '',
        detailJson: {KEY: '0', VALUE: ''},
        selectedAddress: []
      }
    },
    methods: {
      open() {
        this.show = true
      },
      close() {
        this.show = false
      },
      getTabsSelected(item) {
        let flag = false
        if ($Utils.isNull(this.tabsCard)) {
          flag = this.tabsList.length == this.tabsList.indexOf(item) + 1
        } else {
          flag = this.tabsCard['KEY'] == item['KEY']
        }
        return flag
      },
      selected(item) {
        this.tabs = item
        this.tabsCard = {}
        this.tabsList.length = item['LEVELS']
        this.tabsList[item['LEVELS'] - 1] = item
        if (item['MJBJ'] == 0) {
          this.tabsList[item['LEVELS']] = {VALUE: '请选择'}
          this.contentList = []
          this.getContentList(item['KEY'])
        } else {
          let tabsList = []
          let n = 0
          for (let i = 0; i < this.tabsList.length; i++) {
            let tab = this.tabsList[i]
            if (n == 1) break
            if (item['KEY'] == tab['KEY']) n = 1
            tabsList.push(tab)
          }

          this.selectedAddress = tabsList

          this.show = false
        }
      },
      isSelected(item) {
        let flag = item['KEY'] == this.tabs['KEY']
        if (flag) {
          let element = document.getElementById(item['KEY'])
          if (element) element.scrollIntoView()
        }
        return flag
      },
      changeTabs(item) {
        let parent
        if (item['KEY']) {
          parent = this.tabsList[item['LEVELS'] - 2] || {}
          this.tabs = item
          this.tabsCard = item
        } else {
          parent = this.tabsList[this.tabsList.length - 2] || {}
          this.tabsCard = {}
        }
        this.contentList = []
        this.getContentList(parent['KEY'])
      },
      async getAddressListByKey(key) {
        let address = await this.getAddressByKey(key)
        let list = [address]
        for (let i = address['LEVELS'] - 1; i >= 1; i--) {
          let item = await this.getAddressByKey(address['LAST'])
          list.push(item)
        }
        list = list.reverse()
        if (list[list.length - 1]['MJBJ'] == 0) {
          list.push({VALUE: '请选择'})
        }
        return list
      },
      getAddressByKey(key) {
        return new Promise(resolve => {
          let params = {}
          if (parent) params['DQXX01'] = key
          http.get('/api/JLInterface/getDQXX.do', {
            XmlData: JSON.stringify(params)
          }).then(v => {
            let list = v.data['returnList'] || []
            if (!$Utils.isNull(list)) resolve(list[0])
          })
        })
      },
      getContentList(parent) {
        let params = {}
        if (parent) params['PARENT'] = parent
        http.get('/api/JLInterface/getDQXX.do', {
          XmlData: JSON.stringify(params)
        }).then(v => {
          let data = v.data['returnList'];
          for (let i = 0; i < data.length; i++) {
            data[i]['id'] = data[i]['KEY'];
            data[i]['index'] = data[i]['LEVELS']
          }
          this.contentList = data || []
        })
      },
      getAddressName() {
        let data = this.selectedAddress
        let addressName = ''
        for (let i = 0; i < data.length; i++) {
          if (i > 0 && data[i - 1].MJBJ == 1) {
            break
          }
          addressName += data[i].VALUE
          if (data[i].MJBJ != 1) addressName += '-'
        }
        this.addressName = addressName
      },
      init() {
        try {
          let addressList = [...[], ...this.value]

          let adcode = sessionStorage.getItem('AMap.adcode')
          let parent = adcode
          if (!$Utils.isNull(addressList)) {
            for (let i = 0; i < addressList.length; i++) {
              if (i > 0 && addressList[i].MJBJ == 1) {
                parent = addressList[i - 1]
              }
              if ($Utils.isNull(addressList[i].MJBJ)) {
                this.detailJson = addressList[i]
                addressList.splice(i, 1)
              }
            }
            this.selectedAddress = addressList
            this.tabsList = addressList
            parent = parent['KEY']
          } else if (adcode) {
            this.getAddressListByKey(adcode).then(v => {
              this.tabsList = v
            })
          }
          this.getContentList(parent)
        } catch (e) {
        }
      },
      sendData() {
        let res = [...[], ...this.selectedAddress]
        res.push(this.detailJson)
        this.$emit('input', res)
      }
    },
    created() {
      this.init()
    },
    watch: {
      detail() {
        this.sendData()
      },
      selectedAddress() {
        this.getAddressName()
        this.sendData()
      }
    }
  }
</script>

<style scoped>

</style>
